package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.CateLog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    // Map<String,Object> cache = new HashMap<>();
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 从数据库中获取所有分类实体的列表
        List<CategoryEntity> categoryEntities = categoryDao.selectList(null);

        // 使用流式处理构建分类树
        // 首先筛选出所有顶级分类（父分类ID为0）
        // 然后为每个顶级分类设置其子分类
        // 最后对分类进行排序（根据sort字段，若为null则视为0）
        List<CategoryEntity> level1 = categoryEntities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0) // 筛选顶级分类
                .map(menu -> {
                    // 为当前分类设置子分类
                    menu.setChildren(getChildren(menu, categoryEntities));
                    return menu;
                })
                .sorted((menu1, menu2) -> {
                    // 排序逻辑：根据sort字段排序，若为null则视为0
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList()); // 将流转换回列表

        // 返回构建好的顶级分类列表，每个顶级分类都包含了其子分类的树形结构
        return level1;
    }

    @Override
    public void removeMenuByIds(List<Long> list) {
        //TODO 1检查当前删除菜单，是否被别的地方引用
        categoryDao.deleteBatchIds(list);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);

        return parentPath.toArray(new Long[parentPath.size()]);
    }



    /**
     * 级联更新所有数据			[分区名默认是就是缓存的前缀] SpringCache: 不加锁
     *
     * @CacheEvict: 缓存失效模式		--- 页面一修改 然后就清除这两个缓存
     * key = "'getLevel1Categorys'" : 记得加单引号 [子解析字符串]
     *
     * @Caching: 同时进行多种缓存操作
     *
     * @CacheEvict(value = {"category"}, allEntries = true) : 删除这个分区所有数据
     *
     * @CachePut: 这次查询操作写入缓存
     */
    @Caching(evict = {
            @CacheEvict(value = "category",key = "'getLevel1CategoryService'"),
            @CacheEvict(value = "category",key = "'getCataLogJson'")
    })
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updatecategory(category.getCatId(), category.getName());

    }
    @Cacheable(value = {"category"},key = "#root.method.name")  //这注解代表当前结果需要缓存，如果缓存有，方法不调用，如果缓存没有，会调用方法，将结果放入缓存
    @Override
    public List<CategoryEntity> getLevel1CategoryService() {

        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }
    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<String, List<CateLog2Vo>> getCataLogJson() {
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        System.out.println("查询了数据库-------------");
        List<CategoryEntity> level1CategoryService =getParentCid(selectList,0L);
        Map<String, List<CateLog2Vo>> parentCid = level1CategoryService.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> categoryEntities = getParentCid(selectList,v.getCatId());
            List<CateLog2Vo> cateLog2VoList = null;
            if (categoryEntities != null) {
                cateLog2VoList = categoryEntities.stream().map(l2 -> {
                    CateLog2Vo cateLog2Vo = new CateLog2Vo(l2.getCatId().toString(), l2.getName(), v.getCatId().toString(), null);
                    List<CategoryEntity> level3CateLog = getParentCid(selectList,l2.getCatId());
                    if (level3CateLog != null) {
                        List<CateLog2Vo.Catalog3Vo> log3Vos = level3CateLog.stream().map(l3 -> {
                            CateLog2Vo.Catalog3Vo cateLog3Vo = new CateLog2Vo.Catalog3Vo(l3.getCatId().toString(), l3.getName(), l2.getCatId().toString());
                            return cateLog3Vo;
                        }).collect(Collectors.toList());
                        cateLog2Vo.setCatalog3List(log3Vos);
                    }
                    return cateLog2Vo;
                }).collect(Collectors.toList());
            }

            return cateLog2VoList;
        }));
        return parentCid;

    }


    public Map<String, List<CateLog2Vo>> getCataLogJson2() {
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");

        System.out.println(catalogJSON+"-----------------------------------------------");
        if (StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<CateLog2Vo>> cataLogJsonFromDb = getCataLogJsonRedisFromDbWithLocalLock();
            return cataLogJsonFromDb;
        }

        Map<String, List<CateLog2Vo>> cataLogJsonFromDb = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<CateLog2Vo>>>() {
        });//字符串转成对应的类型
        return cataLogJsonFromDb;

    }

    @Cacheable(value = "category", key = "#root.methodName")
    //从数据库查询数据返回
    public Map<String, List<CateLog2Vo>> getCataLogJsonFromDbWithLocalLock() {
        //如果缓存有，用缓存
//        Map<String, List<CateLog2Vo>> cataLogJson = (Map<String, List<CateLog2Vo>>) cache.get("getCataLogJson");
//        if (cache.get("getCataLogJson")==null){
        synchronized (this) {
            return getDataFromDb();
        }

        //}
//       return cataLogJson;
    }

    public Map<String, List<CateLog2Vo>> getCataLogJsonRedissonFromDbWithLocalLock() {//用reids做分布式锁
        //分布式锁，去redis占坑
        RLock lock = redisson.getLock("catalogjson-lock");//占一个锁
        lock.lock();//加一把锁
        Map<String, List<CateLog2Vo>> dataFromDb;

        try {
            dataFromDb = getDataFromDb();
        } finally {
           lock.unlock();//解锁
        }
        return dataFromDb;
    }



    public Map<String, List<CateLog2Vo>> getCataLogJsonRedisFromDbWithLocalLock() {//用reids做分布式锁
            //分布式锁，去redis占坑
        String uuid = UUID.randomUUID().toString();

        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);//不存在才能set;
        String s = stringRedisTemplate.opsForValue().get(uuid);
        System.out.println(s);
        Map<String, List<CateLog2Vo>> dataFromDb =null;
        if (lock){//加锁成功
            try {
              dataFromDb = getDataFromDb();
            }finally {
                //解锁
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                Long lock1 = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }
            //要原子操作才能删除
//            //stringRedisTemplate.delete("lock");
//            String s = stringRedisTemplate.opsForValue().get("lock");
//            if (s.equals(uuid)){
//                stringRedisTemplate.delete("lock");
//            }

            return dataFromDb;
        }else {
            //失败就调用本方法重试
            try {
                Thread.sleep(200);
            }catch (Exception e){}

          return   getCataLogJsonRedisFromDbWithLocalLock();
        }



        //}
//       return cataLogJson;
    }

    private Map<String, List<CateLog2Vo>> getDataFromDb() {
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)){
            Map<String, List<CateLog2Vo>> cataLogJsonFromDb=JSON.parseObject(catalogJSON,new TypeReference<Map<String, List<CateLog2Vo>>>(){});//字符串转成对应的类型
            return cataLogJsonFromDb;
        }
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        List<CategoryEntity> level1CategoryService =getParentCid(selectList,0L);
        Map<String, List<CateLog2Vo>> parentCid = level1CategoryService.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> categoryEntities = getParentCid(selectList,v.getCatId());
            List<CateLog2Vo> cateLog2VoList = null;
            if (categoryEntities != null) {
                cateLog2VoList = categoryEntities.stream().map(l2 -> {
                    CateLog2Vo cateLog2Vo = new CateLog2Vo(l2.getCatId().toString(), l2.getName(), v.getCatId().toString(), null);
                    List<CategoryEntity> level3CateLog = getParentCid(selectList,l2.getCatId());
                    if (level3CateLog != null) {
                        List<CateLog2Vo.Catalog3Vo> log3Vos = level3CateLog.stream().map(l3 -> {
                            CateLog2Vo.Catalog3Vo cateLog3Vo = new CateLog2Vo.Catalog3Vo(l3.getCatId().toString(), l3.getName(), l2.getCatId().toString());
                            return cateLog3Vo;
                        }).collect(Collectors.toList());
                        cateLog2Vo.setCatalog3List(log3Vos);
                    }
                    return cateLog2Vo;
                }).collect(Collectors.toList());
            }

            return cateLog2VoList;
        }));
//            cache.put("getCataLogJson",parentCid);
        //查询出数据，放入缓存
        String jsonString = JSON.toJSONString(parentCid);//转成字符串json
        stringRedisTemplate.opsForValue().set("catalogJSON",jsonString,1,TimeUnit.DAYS);
        return parentCid;
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList,Long parentCid) {
       // return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        List<CategoryEntity> collect = selectList.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == parentCid).collect(Collectors.toList());
        return collect;
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }
    // 递归方法，用于为给定的分类设置其子分类
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        // 使用流式处理筛选出当前分类的所有子分类
        // 然后为每个子分类递归设置其子分类
        // 最后对子分类进行排序（根据sort字段，若为null则视为0）
        List<CategoryEntity> children = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId()) // 筛选当前分类的子分类
                .map(categoryEntity -> {
                    // 为每个子分类递归设置其子分类
                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                    return categoryEntity;
                })
                .sorted((menu1, menu2) -> {
                    // 排序逻辑：根据sort字段排序，若为null则视为0
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList()); // 将流转换回列表

        // 返回当前分类的子分类列表
        return children;
    }
}